<template>
 <div class="user">
  <h2>修改用户名</h2>
  <el-form 
    ref="nameForm" 
    :model="nameForm" 
    :rules="nameRules"
    label-width="100px"
  >
    <el-form-item label="当前用户名 :">
      <span> {{userInfo.name}}</span>
    </el-form-item>
    <el-form-item label="新用户名 :" prop="name">
      <el-input type="text" v-model="nameForm.name"></el-input>
    </el-form-item>
    <el-button type="primary" @click="altName">修改用户名</el-button>
  </el-form>
 </div>
</template>
 
<script>
import {mapState,mapMutations} from "vuex"

export default {
  name: 'AltName',
  data(){
    return{
      nameForm:{
        name:""
      },
      nameRules:{
        name:[
          { required: true, trigger: 'blur' },
          {
            validator:(rule,value,cb)=>{
              if(value === this.userInfo.name){
                cb(new Error("修改后的用户名不能与原用户名相同"))
              }
              cb()
            }
          }
        ]
      }
    }
  },
  methods:{
    ...mapMutations(["altUserInfo"]),
    // 修改用户名
    async altName(){
      this.$refs.nameForm.validate(async v=>{
        if(!v) return false
        let {data} = await this.$axios.post("/client/user/altname",{
          name:this.nameForm.name
        })
        if(data.code) return this.$message.warning(data.mes)
        // 更新vuex
        this.altUserInfo(data.data)
        this.$message.success(data.mes)
        // 清空表单
        this.$refs.nameForm.resetFields() 
      })
    }
  },
  computed:{
    ...mapState(["userInfo"])
  }
}
</script>

<style scoped lang='less'>
.user{
    margin-bottom: 45px;
    h2{
      width: 100%;
      height: 50px;
      line-height: 40px;
      font-size: 20px;
      color: purple;
      box-sizing: border-box;
      border-bottom: 1px solid #eee;
    }
    #name{
      background-color: rgb(230, 229, 229);
      color: red;
      padding: 5px 10px;
    }
}
</style>